package com.frank.code_notes.C01_array;

/**
 * @Description 209. 长度最小的子数组
 * @Author zhoujr
 * @Data 2024/11/24 16:16
 */
public class L209MinSubArray {

    /**
     * @Description 暴力双循环，时间复杂度O(n^2)
     */
    public static int minSubArrayLen(int target, int[] nums) {
        int res = Integer.MAX_VALUE, count = 0, subLength = 0;
        for (int i = 0; i < nums.length; i++) {
            count = 0;
            for (int j = i; j < nums.length; j++) {
                count += nums[j];
                if (count >= target) {
                    res = Math.min(res, j - i + 1);
                    break;
                }
            }
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }

    /**
     * @Description 滑窗算法可以理解为双指针算法的一种，时间复杂度O(n)
     */
    public static int minSubArrayLenTwo(int target, int[] nums) {
        int res = Integer.MAX_VALUE;
        int count = 0; // 滑动窗口内总和
        int i = 0;
        for (int j = 0; j < nums.length; j++) { // 滑动窗口结束位置移动
            count += nums[j];
            while (count >= target) {
                res = Math.min(res, j - i + 1);
                count -= nums[i++]; // 滑动窗口开始位置移动
            }
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }

    public static void main(String[] args) {
        System.out.println(minSubArrayLen(7, new int[]{2, 3, 1, 2, 4, 1, 3}));
        System.out.println(minSubArrayLenTwo(7, new int[]{2, 3, 1, 2, 4, 1, 3}));
    }

}
